package zy.controller.base;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import jxl.Workbook;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import zy.controller.BaseController;
import zy.entity.PageData;
import zy.entity.base.brand.T_Base_Brand;
import zy.entity.base.color.T_Base_Color;
import zy.entity.sys.improtinfo.T_Import_Info;
import zy.entity.sys.user.T_Sys_User;
import zy.form.PageForm;
import zy.service.base.brand.BrandService;
import zy.util.CommonUtil;
import zy.util.DateUtil;
import zy.util.ExcelImportUtil;
import zy.util.StringUtil;

@Controller
@RequestMapping("base/brand")
public class BrandController extends BaseController{
	
	@Resource
	private BrandService brandService;

	@RequestMapping(value = "/to_list", method = RequestMethod.GET)
	public String to_list() {
		return "base/brand/list";
	}
	
	@RequestMapping(value = "/to_update", method = RequestMethod.GET)
	public String to_update(@RequestParam Integer bd_id,Model model) {
		T_Base_Brand brand = brandService.queryByID(bd_id);
		if(null != brand){
			model.addAttribute("brand",brand);
		}
		return "base/brand/update";
	}
	
	@RequestMapping("to_add")
	public String to_add() {
		return "base/brand/add";
	}
	
	/**
	 * 查询品牌弹出框页面，支持单选和多选
	 */
	@RequestMapping("to_list_dialog")
	public String to_list_dialog() {
		return "base/brand/list_dialog";
	}
	
	@RequestMapping("to_import_brand")
	public String to_import_color() {
		return "base/brand/import_brand";
	}
	
	@RequestMapping(value = "page", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object page(PageForm pageForm,HttpSession session) {
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("searchContent", pageForm.getSearchContent());
        param.put(CommonUtil.PAGESIZE, pageForm.getRows());
        param.put(CommonUtil.PAGEINDEX, pageForm.getPage());
        param.put(CommonUtil.SIDX, pageForm.getSidx());
        param.put(CommonUtil.SORD, pageForm.getSord());
        param.put(CommonUtil.COMPANYID, getCompanyid(session));
        System.out.println("--------"+param);
		PageData<T_Base_Brand> pageData = brandService.page(param);
		return ajaxSuccess(pageData);
	}
	
	@RequestMapping(value = "save", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object save(T_Base_Brand brand,HttpServletRequest request,HttpSession session) {
		 T_Sys_User user = getUser(session);
		 brand.setCompanyid(user.getCompanyid());
		 brand.setBd_spell(StringUtil.getSpell(brand.getBd_name()));
		 Integer id = brandService.queryByName(brand);
		 if(null != id && id > 0){
			return result(EXISTED);
		 }else{
			 brandService.save(brand);
			 return ajaxSuccess(brand);
		 }
	}
	
	@RequestMapping(value = "update", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object update(T_Base_Brand brand,HttpServletRequest request,HttpSession session) {
		T_Sys_User user = getUser(session);
		brand.setCompanyid(user.getCompanyid());
		brand.setBd_spell(StringUtil.getSpell(brand.getBd_name()));
		Integer id = brandService.queryByName(brand);
		if (null != id && id > 0) {
			return result(EXISTED);
		} else {
			brandService.update(brand);
			return ajaxSuccess(brand);
		}
	}
	
	@RequestMapping(value = "del", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Object del(@RequestParam Integer bd_id) {
		brandService.del(bd_id);
		return ajaxSuccess();
	}
	
	@RequestMapping(value = "save_import_brand", method = RequestMethod.POST,produces = "text/html; charset=utf-8")
	@ResponseBody
	public Object save_import_brand(MultipartFile excel,HttpServletRequest request,HttpSession session)throws IOException {
		if (excel == null || excel.getSize() <= 0) {
			return ajaxFail("请选择需要导入的文件！"); 
		}
		Map<String,Object> param = new HashMap<String, Object>();
		Workbook sourceWorkBook = null;
		Workbook wb_error = null;
		WritableWorkbook wb = null;
		
		try {
			T_Sys_User user = getUser(session);
			param.put("companyid", user.getCompanyid());
			param.put("us_id", user.getUs_id());
			//根据商家编号、用户编号及当前时间生成文件名
			SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
			String fileName = "brand_" + user.getCompanyid() + (user.getUs_id() + format.format(new Date())) + ".xls";
			
			// 复制客户端文件到服务器临时文件夹进行处理,处理完以后删除
			String temp_uploaddir = CommonUtil.CHECK_BASE + CommonUtil.EXCEL_PATH;
			String toFilePath = temp_uploaddir + File.separator + fileName;
			File savefile = new File(toFilePath);
			if (!savefile.getParentFile().exists()) {
				savefile.getParentFile().mkdirs();
			}
			excel.transferTo(savefile);
			
			// Excel 模板文件路径，把模板文件复制，然后作为错误文件进行数据追加
			String relPath = session.getServletContext().getRealPath("resources");
			String excel_member_template = relPath + File.separator + "excel" + File.separator + CommonUtil.BRANDLEADING;
			
			// 错误文件名称
			String errFileName = "fail" + fileName;
			String errorFilePath = temp_uploaddir + File.separator + errFileName;
			File excel_template = new File(excel_member_template);// 原有Excel 模板文件
			File errorFile = new File(errorFilePath);// 生成的错误文件路径
			// 把模板文件复制给错误文件
			FileUtils.copyFile(excel_template, errorFile);
			
			sourceWorkBook = Workbook.getWorkbook(savefile);// 要导入的Excel
			wb_error = Workbook.getWorkbook(errorFile);
			wb = Workbook.createWorkbook(errorFile, wb_error);
			Map<String, Object> result = brandService.parseSavingBrandExcel(sourceWorkBook, wb, user.getCompanyid());
			wb.write();
			
			ExcelImportUtil.deleteFile(savefile);
			int success = (Integer)(result.get("success"));// 导入成功条数
			int fail = (Integer)(result.get("fail"));// 导入失败条数
			List<T_Base_Brand> brandList = (List<T_Base_Brand>)result.get("brandList");//导入成功数据
			param.put("brandList", brandList);
			
			T_Import_Info t_Import_Info = new T_Import_Info();
			t_Import_Info.setIi_success(success);
			t_Import_Info.setIi_fail(fail);
			t_Import_Info.setIi_total(success+fail);
			t_Import_Info.setIi_filename(excel.getOriginalFilename());
			t_Import_Info.setIi_error_filename(errFileName);
			t_Import_Info.setIi_us_id(user.getUs_id());
			t_Import_Info.setIi_sysdate(DateUtil.getCurrentTime());
			t_Import_Info.setIi_type(CommonUtil.IMPROT_BRANDTYPE);
			t_Import_Info.setCompanyid(user.getCompanyid());
			param.put("t_Import_Info", t_Import_Info);
			param.put("ii_type", CommonUtil.IMPROT_BRANDTYPE);
			
			brandService.save(param);
		}  catch (Exception e){
			e.printStackTrace();
			return ajaxFail("导入失败，请联系管理员！");
		} finally {
			if (sourceWorkBook != null)
				sourceWorkBook.close();
			if (wb_error != null)
				wb_error.close();
			try {
				if (wb != null)
					wb.close();
			} catch (WriteException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		return ajaxSuccess();
	}
}
